package com.faiz.algorithm;


public class DecodeString {
    private int index = 0;

    public String decodeString(String s) {
        // 使用递归的思路来解决
        return dfs(s);
    }

    public String dfs(String s) {

        StringBuffer res = new StringBuffer();
        String resSuffix = "";
        int multi = 0;

        while (index < s.length()) {
            char c = s.charAt(index);
            if (isDigit(c)) {
                multi = multi * 10 + Integer.parseInt(c + "");
                index++;
            } else if (c == '[') {
                index++;
                resSuffix = dfs(s);

                StringBuffer tmp = new StringBuffer();
                for (int i = 0; i < multi; i++) tmp.append(resSuffix);
                // 使用过一次之后要重置
                multi = 0;
                res.append(tmp);

            } else if (c == ']') {
                index++;
                return res.toString();
            } else {
                res.append(c);
                index++;
            }
        }

        return res.toString();
    }

    private boolean isDigit(char c) {
        return c >= '0' && c <= '9';
    }

    public static void main(String[] args) {
        String s = "3[a]2[b]";
        DecodeString decodeString = new DecodeString();
        System.out.println(decodeString.decodeString(s));
    }
}
